<?php
	error_reporting(E_ALL || ~E_NOTICE);

	$skid = $_POST["skid"];
	$controlernum = $_POST["controlernum"];	
	$gatenum = $_POST["gatenum"];
	$WebADDR = $_POST["serverIP"];
	$WebPORT = $_POST["serverPORT"];
	$TcpPORT = $_POST["tcpPORT"];
//	$cmdresultpath = $_POST["cmdresult"];
	$realtimepath = $_POST["realtimepath"];
//	$DetectDevicepath = $_POST["DetectDevice"];
	$CameraADDR = $_POST["CameraADDR"];
	$CameraPORT = $_POST["CameraPORT"];
	$CameraRTSP = $_POST["CameraRTSP"];

	$jianquanfangshi = $_POST["jianquanfangshi"];

	file_put_contents("test.log", "skid ".$skid." controlernum ".$controlernum." gatenum ".$gatenum." WebADDR ".$WebADDR." WebPORT ".$WebPORT." TcpPORT ".$TcpPORT." realtimepath ".$realtimepath." CameraADDR ".$CameraADDR." $CameraPORT ".$$CameraPORT." CameraRTSP ".$CameraRTSP." line: ".__LINE__."\n", FILE_APPEND);

//		if(!$WebADDR||!$WebPORT||!$TcpPORT||!$realtimepath||!$Camera0ADDR||!$Camera0PORT||!$Camera1ADDR||!$Camera1PORT||!$sVersion||!$jianquanfangshi)
	if(!$WebADDR||!$WebPORT||!$TcpPORT||!$realtimepath||!$CameraADDR||!$CameraPORT ||!$jianquanfangshi || $gatenum===NULL)
	{	    
		echo "<script language=\"JavaScript\">alert('输入为空或太长。');</script><br/>";
//		echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='/door/gatesetting.php',500);</script><br/>";	
//			file_put_contents("test.log", "\n null \n", FILE_APPEND);
		return;	
	}
	$gatename='大门';
	$controlmethod='card';
	$delayopentime='0';
	$delayclosetime='0';
	$sensorstat='NG';
	$attendancecheck='yes';
	$region='总部';
	$antipassback='no';

	$strSql='';
	$dbResult=array();  
	$myconn=dwopendb();
	if($controlernum ==="ALL")
	{
		$strSql="SELECT DISTINCT controlerNum,lasttime FROM gatesetting WHERE controlerNum !='ALL' ORDER BY lasttime DESC;";
		$result=mysql_query($strSql,$myconn);
//			$result=mysql_query($strSql);
		while($dbResult = mysql_fetch_row($result))
		{
			if($gatenum==="all")
			{
//					dwclosedb($myconn);
				for($i=0;$i<4;$i++)
				{	
					$strSql="UPDATE gatesetting SET serverIP='$WebADDR',serverPORT='$WebPORT',tcpPORT='$TcpPORT',jianquanfangshi='$jianquanfangshi',realtimepath='$realtimepath',CameraADDR='$CameraADDR',CameraPORT='$CameraPORT',CameraRTSP='$CameraRTSP' WHERE controlerNum = '$dbResult[0]' AND gatenum= '$i';";
					$result11=mysql_query($strSql,$myconn);
					@file_put_contents("test.log", "\n strSql00 =".$strSql." line: ".__LINE__."\n", FILE_APPEND);
					if((mysql_affected_rows()==0) or (mysql_affected_rows()==-1))
					{ 
						mysql_free_result($result11);
						dwclosedb($myconn);
						echo "<script language=\"JavaScript\">alert(\"下发失败。\");</script><br/>";	
//						echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='/door/gatesetting.php',500);</script><br/>";	
						return;							
					} 
					mysql_free_result($result11);

					$transid=uuid();
			
					$cmdstr="{\"dwdevice\":\"". $dbResult[0]."\",\"trans_id\":\"".$transid."\",\"cmd_code\":\"DW_SET_DEVICEINFO\",\"gatename\":\"$gatename\",\"controlmethod\":\"$controlmethod\",\"delayopentime\":\"$delayopentime\",\"delayclosetime\":\"".$delayclosetime."\",\"sensorstat\":\"$sensorstat\",\"gatenumber\":\"$i\",\"readerfunction\":\"26\",\"attendancecheck\":\"".$attendancecheck."\",\"region\":\"".$region."\",\"password\":\"888888\",\"forcepass\":\"999999\",\"antipassback\":\"".$antipassback."\",\"url\":\"$WebADDR\",\"port\":\"$WebPORT\",\"tcpport\":\"$TcpPORT\",\"jianquanfangshi\":\"$jianquanfangshi\",\"realtimepath\":\"$realtimepath\",\"CameraADDR\":\"$CameraADDR\",\"CameraPORT\":\"$CameraPORT\"}";
					dwsendtoserver($cmdstr,$myconn);
					file_put_contents("test.log", "\n cmdstr_0: ".$cmdstr." TCPport: ".$TCPport." line: ".__LINE__."\n", FILE_APPEND);
				}
			}else
			{
				$strSql="UPDATE gatesetting SET gatename='$gatename',controlmethod='$controlmethod',delayopentime='$delayopentime',delayclosetime='$delayclosetime',sensorstat='$sensorstat',attendancecheck='$attendancecheck',region='$region',antipassback='$antipassback',serverIP='$WebADDR',serverPORT='$WebPORT',tcpPORT='$TcpPORT',jianquanfangshi='$jianquanfangshi',realtimepath='$realtimepath',CameraADDR='$CameraADDR',CameraPORT='$CameraPORT',CameraRTSP='$CameraRTSP',sVersion='$sVersion' WHERE controlerNum = '$dbResult[0]' AND gatenum= '$gatenum';";
				$result11=mysql_query($strSql,$myconn);
				@file_put_contents("test.log", "\n strSql01 =".$strSql." line: ".__LINE__."\n", FILE_APPEND);
				if(mysql_affected_rows($myconn)==-1)	
				{ 
					mysql_free_result($result11);
					dwclosedb($myconn);
					echo "<script language=\"JavaScript\">alert(\"下发失败。\");</script><br/>";	
//					echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='/door/gatesetting.php',500);</script><br/>";	
					return;	
				} 
				mysql_free_result($result11);

				$transid=uuid();
					
				$cmdstr="{\"dwdevice\":\"".$dbResult[0]."\",\"trans_id\":\"".$transid."\",\"cmd_code\":\"DW_SET_DEVICEINFO\",\"gatename\":\"$gatename\",\"controlmethod\":\"$controlmethod\",\"delayopentime\":\"$delayopentime\",\"delayclosetime\":\"".$delayclosetime."\",\"sensorstat\":\"$sensorstat\",\"gatenumber\":\"$gatenum\",\"readerfunction\":\"26\",\"attendancecheck\":\"".$attendancecheck."\",\"region\":\"".$region."\",\"password\":\"888888\",\"forcepass\":\"999999\",\"antipassback\":\"".$antipassback."\",\"url\":\"$WebADDR\",\"port\":\"$WebPORT\",\"tcpport\":\"$TcpPORT\",\"jianquanfangshi\":\"$jianquanfangshi\",\"realtimepath\":\"$realtimepath\",\"CameraADDR\":\"$CameraADDR\",\"CameraPORT\":\"$CameraPORT\"}";
				dwsendtoserver($cmdstr,$myconn);
				file_put_contents("test.log", "\n cmdstr_1: ".$cmdstr." TCPport: ".$TCPport." line: ".__LINE__."\n", FILE_APPEND);
			}
		}	
	}else if($controlernum)
	{
		$strSql="SELECT MAX(skid) FROM gatesetting WHERE controlerNum ='$controlernum';";
		$result=mysql_query($strSql,$myconn);
		$dbResult = mysql_fetch_array($result);
		mysql_free_result($result);
	//	file_put_contents("test.log", "\n strSql".$strSql, FILE_APPEND);
		if($dbResult[0])
		{
			if($gatenum==="all")
			{
				for($i=0;$i<4;$i++)
				{					
					$strSql="UPDATE gatesetting SET gatename='$gatename',controlmethod='$controlmethod',delayopentime='$delayopentime',delayclosetime='$delayclosetime',sensorstat='$sensorstat',attendancecheck='$attendancecheck',region='$region',antipassback='$antipassback',serverIP= '$WebADDR',serverPORT='$WebPORT',tcpPORT='$TcpPORT',jianquanfangshi='$jianquanfangshi',realtimepath='$realtimepath',CameraADDR='$CameraADDR',CameraPORT='$CameraPORT',CameraRTSP='$CameraRTSP',sVersion='$sVersion' WHERE controlerNum ='$controlernum' AND gatenum= '$i';";
					$result=mysql_query($strSql,$myconn);
					@file_put_contents("test.log", "\n strSql02 =".$strSql." line: ".__LINE__."\n", FILE_APPEND);
					if(mysql_affected_rows($myconn)==-1)
					{ 
						mysql_free_result($result);
						dwclosedb($myconn);
						echo "<script language=\"JavaScript\">alert(\"下发失败。\");</script><br/>";	
						file_put_contents("test.log", "\n strSql02 =".$strSql." mysql_error: ".mysql_error()." line: ".__LINE__."\n", FILE_APPEND);
	//					echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='/door/gatesetting.php',500);</script><br/>";	
						return;	
					} 
					mysql_free_result($result);
					$cmdstr="{\"dwdevice\":\"".$controlernum."\",\"trans_id\":\"".uuid()."\",\"cmd_code\":\"DW_SET_DEVICEINFO\",\"gatename\":\"$gatename\",\"controlmethod\":\"$controlmethod\",\"delayopentime\":\"$delayopentime\",\"delayclosetime\":\"".$delayclosetime."\",\"sensorstat\":\"$sensorstat\",\"gatenumber\":\"$i\",\"readerfunction\":\"26\",\"attendancecheck\":\"".$attendancecheck."\",\"region\":\"".$region."\",\"password\":\"888888\",\"forcepass\":\"999999\",\"antipassback\":\"".$antipassback."\",\"url\":\"$WebADDR\",\"port\":\"$WebPORT\",\"tcpport\":\"$TcpPORT\",\"jianquanfangshi\":\"$jianquanfangshi\",\"realtimepath\":\"$realtimepath\",\"CameraADDR\":\"$CameraADDR\",\"CameraPORT\":\"$CameraPORT\"}";
					
					dwsendtoserver($cmdstr,$myconn);
					file_put_contents("test.log", "\n cmdstr_2: ".$cmdstr." TCPport: ".$TCPport." 	LINE ".__LINE__."\n", FILE_APPEND);
				}
			}else
			{
				$strSql="UPDATE gatesetting SET gatename='$gatename',controlmethod='$controlmethod',delayopentime='$delayopentime',delayclosetime='$delayclosetime',sensorstat='$sensorstat',attendancecheck='$attendancecheck',region='$region',antipassback='$antipassback',serverIP= '$WebADDR',serverPORT='$WebPORT',tcpPORT='$TcpPORT',jianquanfangshi='$jianquanfangshi',realtimepath='$realtimepath',CameraADDR='$CameraADDR',CameraPORT='$CameraPORT',CameraRTSP='$CameraRTSP',sVersion='$sVersion' WHERE controlerNum = '$controlernum' AND gatenum= '$gatenum';";
				$result=mysql_query($strSql,$myconn);
				@file_put_contents("test.log", "\n strSql03 =".$strSql." line ".__LINE__."\n", FILE_APPEND);
				if(mysql_affected_rows($myconn)==-1)	
				{ 
					mysql_free_result($result11);
					dwclosedb($myconn);
					echo "<script language=\"JavaScript\">alert(\"下发失败。\");</script><br/>";	
//					echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='/door/gatesetting.php',500);</script><br/>";	
					return;	
				} 
				mysql_free_result($result);
				$cmdstr="{\"dwdevice\":\"".$controlernum."\",\"trans_id\":\"".uuid()."\",\"cmd_code\":\"DW_SET_DEVICEINFO\",\"gatename\":\"$gatename\",\"controlmethod\":\"$controlmethod\",\"delayopentime\":\"$delayopentime\",\"delayclosetime\":\"".$delayclosetime."\",\"sensorstat\":\"$sensorstat\",\"gatenumber\":\"$gatenum\",\"readerfunction\":\"26\",\"attendancecheck\":\"".$attendancecheck."\",\"region\":\"".$region."\",\"password\":\"888888\",\"forcepass\":\"999999\",\"antipassback\":\"".$antipassback."\",\"url\":\"$WebADDR\",\"port\":\"$WebPORT\",\"tcpport\":\"$TcpPORT\",\"jianquanfangshi\":\"$jianquanfangshi\",\"realtimepath\":\"$realtimepath\",\"CameraADDR\":\"$CameraADDR\",\"CameraPORT\":\"$CameraPORT\"}";
				
				dwsendtoserver($cmdstr,$myconn);
				file_put_contents("test.log", "\n cmdstr_3: ".$cmdstr." TCPport: ".$TCPport." line: ".__LINE__."\n", FILE_APPEND);
			}
		}else
		{
			if($gatenum==="all")
			{
				for($i=0;$i<4;$i++)
				{
					$strSql="INSERT INTO gatesetting(controlerNum,gatenum,gatename,controlmethod,delayopentime,delayclosetime,sensorstat,attendancecheck,region,antipassback,serverIP,serverPORT,tcpPORT,jianquanfangshi,realtimepath,CameraADDR,CameraPORT,CameraRTSP,sVersion,IP,PORT,lianjie,lasttime) VALUES('".$controlernum."','$i','$gatename','$controlmethod','$delayopentime','$delayclosetime','$sensorstat','$attendancecheck','$region','$antipassback','$WebADDR','$WebPORT','$TcpPORT','$jianquanfangshi','$realtimepath','$CameraADDR','$CameraPORT','$CameraRTSP','$sVersion','127.0.0.1','80','offline','2016-01-01 00:00:00');";
					$result=mysql_query($strSql,$myconn);
					@file_put_contents("test.log", "\n strSql04 =".$strSql." line: ".__LINE__."\n", FILE_APPEND);
					if((mysql_affected_rows($myconn)==0) or (mysql_affected_rows($myconn)==-1))	
					{ 
						mysql_free_result($result11);
						dwclosedb($myconn);
						echo "<script language=\"JavaScript\">alert(\"下发失败。\");</script><br/>";	
	//					echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='/door/gatesetting.php',500);</script><br/>";	
						return;	
					} 
					$cmdstr="{\"dwdevice\":\"".$controlernum."\",\"trans_id\":\"".uuid()."\",\"cmd_code\":\"DW_SET_DEVICEINFO\",\"gatename\":\"$gatename\",\"controlmethod\":\"$controlmethod\",\"delayopentime\":\"$delayopentime\",\"delayclosetime\":\"".$delayclosetime."\",\"sensorstat\":\"$sensorstat\",\"gatenumber\":\"$i\",\"readerfunction\":\"26\",\"attendancecheck\":\"".$attendancecheck."\",\"region\":\"".$region."\",\"password\":\"888888\",\"forcepass\":\"999999\",\"antipassback\":\"".$antipassback."\",\"url\":\"$WebADDR\",\"port\":\"$WebPORT\",\"tcpport\":\"$TcpPORT\",\"jianquanfangshi\":\"$jianquanfangshi\",\"realtimepath\":\"$realtimepath\",\"CameraADDR\":\"$CameraADDR\",\"CameraPORT\":\"$CameraPORT\"}";
					mysql_free_result($result);

					dwsendtoserver($cmdstr,$myconn);
					file_put_contents("test.log", "\n cmdstr_4: ".$cmdstr." line: ".__LINE__."\n", FILE_APPEND);
				}
			}else
			{
				$strSql="INSERT INTO gatesetting(controlerNum,gatenum,gatename,controlmethod,delayopentime,delayclosetime,sensorstat,attendancecheck,region,antipassback,serverIP,serverPORT,tcpPORT,jianquanfangshi,realtimepath,CameraADDR,CameraPORT,CameraRTSP,sVersion,IP,PORT,lianjie,lasttime) VALUES('".$controlernum."','$gatenum','$gatename','$controlmethod','$delayopentime','$delayclosetime','$sensorstat','$attendancecheck','$region','$antipassback','$WebADDR','$WebPORT','$TcpPORT','$jianquanfangshi','$realtimepath','$CameraADDR','$CameraPORT','$CameraRTSP','$sVersion','127.0.0.1','80','offline','2016-01-01 00:00:00');";
				$result=mysql_query($strSql,$myconn);
				@file_put_contents("test.log", "\n strSql05 =".$strSql."\n", FILE_APPEND);
				if((mysql_affected_rows($myconn)==0) or (mysql_affected_rows($myconn)==-1))	
				{ 
					mysql_free_result($result11);
					dwclosedb($myconn);
					echo "<script language=\"JavaScript\">alert(\"下发失败。\");</script><br/>";	
//					echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='/door/gatesetting.php',500);</script><br/>";	
					return;	
				} 
				$cmdstr="{\"dwdevice\":\"".$controlernum."\",\"trans_id\":\"".uuid()."\",\"cmd_code\":\"DW_SET_DEVICEINFO\",\"gatename\":\"$gatename\",\"controlmethod\":\"$controlmethod\",\"delayopentime\":\"$delayopentime\",\"delayclosetime\":\"".$delayclosetime."\",\"sensorstat\":\"$sensorstat\",\"gatenumber\":\"$gatenum\",\"readerfunction\":\"26\",\"attendancecheck\":\"".$attendancecheck."\",\"region\":\"".$region."\",\"password\":\"888888\",\"forcepass\":\"999999\",\"antipassback\":\"".$antipassback."\",\"url\":\"$WebADDR\",\"port\":\"$WebPORT\",\"tcpport\":\"$TcpPORT\",\"jianquanfangshi\":\"$jianquanfangshi\",\"realtimepath\":\"$realtimepath\",\"CameraADDR\":\"$CameraADDR\",\"CameraPORT\":\"$CameraPORT\"}";
				mysql_free_result($result);

				dwsendtoserver($cmdstr,$myconn);
				file_put_contents("test.log", "\n cmdstr_5: ".$cmdstr." line: ".__LINE__."\n", FILE_APPEND);
			}	
		}
	}
	dwclosedb($myconn);

	echo "<script language=\"JavaScript\">alert('下发成功。');</script><br/>";
//	echo "<script language=\"JavaScript\">self.setTimeout(window.location.href='/door/gatesetting.php',500);</script><br/>";	
	return;

	function uuid() 
	{
        if (function_exists('com_create_guid')) 
		{
            return md5(com_create_guid());
        }else 
		{
            mt_srand((double)microtime()*10000);                   //optional for php 4.2.0 and up.
            $charid = md5(uniqid(rand(),true)); 
            return $charid;
        }
    }

	function dwsendtoserver($msg,$myconn)
	{		
		$strSql="SELECT DISTINCT TcpPORT FROM gatesetting;";
		$result44=mysql_query($strSql,$myconn);
//		$result=mysql_query($strSql);
		$dbResult44 = mysql_fetch_array($result44);
		if($dbResult44[0])
		{
			$TCPport = $dbResult44[0];
		}else
		{
			$TCPport = "1119";
		}
		mysql_free_result($result44);
		if( ($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false)
		{
//	        echo "socket_create() failed :reason:" . socket_strerror(socket_last_error()) . "<br/>";
//	        $string = "socket_create() 1failed :reason:" . socket_strerror(socket_last_error()) . "<br/>";
//	        file_put_contents("test.log", $string, FILE_APPEND);
			socket_clear_error();
			return false;
        }else
		{
//		    echo "socket_create OK.<br/>";
//			$string = "socket_create() 2failed :reason:" . socket_strerror(socket_last_error()) . "<br/>";
//	        file_put_contents("test.log", $string, FILE_APPEND);
		}
		if(socket_connect($sock, '127.0.0.1', $TCPport)===false)
		{
//			file_put_contents("test.log","\n socket_connect1: ".socket_strerror(socket_last_error())."\n", FILE_APPEND);
			socket_clear_error();
			socket_close($sock);
			return false;
		}
		if(socket_sendto($sock, $msg, strlen($msg),0,"127.0.0.1",$TCPport)===false)
		{
//				file_put_contents("test.log","2 \n socket_strerror: ".socket_strerror(socket_last_error())."\n", FILE_APPEND);
//			echo "{\"result\":\"ERROR\"}";
			socket_clear_error();
			socket_close($sock);
			return false;
		}else
		{
//			    echo 'sendto client message:'.$msg3.'message len:'.strlen($msg3).'<br/>';
//				file_put_contents("test.log","3 \n socket_strerror: ".socket_strerror(socket_last_error())."\n", FILE_APPEND);
//			echo "{\"result\":\"OK\"}";
		}
		socket_clear_error();
		socket_close($sock);
		return true;
	}

	function dwclosedb($myconn)
	{
		mysql_close($myconn);	
	}
	
	function dwopendb()
	{
		$myconn=@mysql_connect("localhost","dw","DWdawu-309");
		if(!$myconn)
		{
//			die('Could not connect: '.mysql_error());
			$string = "Can't connect database : ".mysql_error()." LINE:".__LINE__."\n";
			file_put_contents("test.log", $string, FILE_APPEND);
			return false;
		}
		$db_selected=mysql_select_db("dwzuapairenlian",$myconn);
		if(!$db_selected)
		{
//			die("Can't use database dwaccessDB : ".mysql_error());       
			$strSql="CREATE DATABASE dwzuapairenlian;";
			$result=mysql_query($strSql,$myconn);
			if($result==false)
			{
				die("Can't use database dwaccessDB : ".mysql_error());
				$string = "Can't use database : ".mysql_error()." LINE:".__LINE__."\n";
				file_put_contents("test.log", $string, FILE_APPEND);
				dwclosedb($myconn);
				$response = base64_encode("{\"res\":\"deny3\"}");
				echo $response;					
				return false;
			}
			$strSql="set character_set_database=utf8;";
			$result=mysql_query($strSql,$myconn);
	
			mysql_close($myconn);
			return false;
		}
		return $myconn;
	}
?>
